package top.zhangjianyong.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.zhangjianyong.blog.enums.RespCode;
import top.zhangjianyong.blog.entity.po.BlogVisit;
import top.zhangjianyong.blog.mapper.BlogVisitMapper;
import top.zhangjianyong.blog.params.blog.BlogLikeParam;
import top.zhangjianyong.blog.response.ApiResponse;
import top.zhangjianyong.blog.service.BlogService;
import top.zhangjianyong.blog.service.BlogVisitService;

/**
 * @author zhangjianyong
 * @since 2025/6/24 16:29
 */
@Slf4j
@Service
public class BlogVisitServiceImpl extends ServiceImpl<BlogVisitMapper, BlogVisit>
    implements BlogVisitService {

  private final BlogService blogService;

  public BlogVisitServiceImpl(BlogService blogService) {
    this.blogService = blogService;
  }

  @Override
  public ApiResponse save(BlogLikeParam param, String uuid) {
    log.info("保存记录参数：{},{}", uuid, param);
    if (StrUtil.isBlank(uuid)) return ApiResponse.fail(RespCode.FAIL.getCode(), "未获取访客编号");
    if (getOne(param.blogId(), param.type(), uuid) != null) {
      return ApiResponse.fail(RespCode.BLOG_VISIT_EXISTS_FAIL);
    }

    BlogVisit blogVisit = new BlogVisit();
    blogVisit.setBlogId(param.blogId());
    blogVisit.setUuid(uuid);
    blogVisit.setType(param.type());
    if (save(blogVisit)) {
      blogService.addVisit(param.blogId(), param.type());
    }
    return ApiResponse.success();
  }

  @Override
  public BlogVisit getOne(Long blogId, Integer type, String uuid) {
    return lambdaQuery()
        .eq(BlogVisit::getBlogId, blogId)
        .eq(BlogVisit::getUuid, uuid)
        .eq(BlogVisit::getType, type)
        .one();
  }
}
